<template>
  <el-header class="layout-header">
    <div class="logo">
      <router-link to="/">
      <img src="@/assets/images/logo.png" alt="">
      <span>首页</span>     
      </router-link>
    </div>
    <div class="user">
      <el-dropdown @command="handleCommand">
        <span class="user-info">
          <el-avatar :size="30" :src="userInfo.avatar || defaultAvatar" />
          <span class="username">{{ userInfo.username }}</span>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">修改个人信息</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </el-header>

  <!-- 个人信息修改弹窗 -->
  <el-dialog
    v-model="profileDialogVisible"
    title="修改个人信息"
    width="30%"
  >
    <el-form :model="profileForm" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="profileForm.username" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="profileForm.email" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="profileForm.phone" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group  v-model="profileForm.sex">
          <el-radio label="男" value="男"></el-radio>
          <el-radio label="女" value="女"></el-radio>
          <el-radio label="保密" value="保密"></el-radio>
      </el-radio-group>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action='http://localhost:8081/taoxi/upload'
          :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
        >
          <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
          <el-icon v-else><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="profileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateProfile">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <el-container class="layout-container">
    <el-aside width="200px">
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        router
      >
        <el-menu-item index="/factory/info">
          <el-icon><HomeFilled /></el-icon>
          <span>店铺信息</span>
        </el-menu-item>
        <el-menu-item index="/factory/good">
          <el-icon><Goods /></el-icon>
          <span>商品管理</span>
        </el-menu-item>
        <el-menu-item index="/factory/order">
          <el-icon><Checked /></el-icon>
          <span>订单管理</span>
        </el-menu-item>
        <el-menu-item index="/factory/project">
          <el-icon><CollectionTag /></el-icon>
          <span>众筹定制管理</span>
        </el-menu-item>
        <el-menu-item index="/factory/message">
          <el-icon><ChatDotRound /></el-icon>
          <span>我的消息</span>
        </el-menu-item>
        <el-menu-item index="/factory/data">
          <el-icon><Histogram /></el-icon>
          <span>数据可视化</span>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-main>
      <router-view></router-view>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed,reactive } from 'vue'
import { HomeFilled, Goods, Checked,ShoppingCartFull,Histogram,CollectionTag,ChatDotRound} from '@element-plus/icons-vue'
import {useTokenStore } from '@/store/token';
import {useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateUserApi } from '@/api/user'

const route = useRoute()
const activeMenu = computed(() => route.path)

const router = useRouter()
const profileDialogVisible = ref(false)
const tokenStore = useTokenStore();
// 使用ref包装userInfo以实现响应式
const userInfo = ref(tokenStore.user)

// 配置请求头
const headers = {
  Authorization: encodeURIComponent(tokenStore.getToken())
}

const profileForm = reactive({
  userId: '',
  username: '',
  email: '',
  avatar: '',
  phone: '',
  sex: ''
})

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    handleLogout()
  } else if (command === 'profile') {
    showProfileDialog()
  }
}

// 显示个人信息弹窗
const showProfileDialog = () => {
  const { userId, username, avatar, phone, email, sex } = userInfo.value
  Object.assign(profileForm, { userId, username, avatar, phone, email, sex })
  profileDialogVisible.value = true
}

// 处理退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确认退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除登录信息
    tokenStore.removeToken;
    tokenStore.removeUser;
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    // 跳转到登录页
    router.push('/login')
    ElMessage.success('退出成功')
  })
}

// 处理头像上传成功
const handleAvatarSuccess = (res) => {
    if (res.code === 0) {
    profileForm.avatar = res.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}
// 上传失败回调
const handleAvatarError = (error) => {
  console.error('上传错误:', error)
  ElMessage.error('上传失败，请重试')
}

// 处理更新个人信息
const handleUpdateProfile = async () => {
  try {
    await updateUserApi(profileForm)
    // 1. 更新store中的用户信息
    tokenStore.setUser({
      ...tokenStore.user,  // 保留原有信息
      ...profileForm       // 更新修改的字段
    })
    // 2. 更新本地响应式数据
    userInfo.value = tokenStore.user
    profileDialogVisible.value = false
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error(error.message)
  }
}
</script>

<style lang='scss' scoped>
.layout-header {
  display: flex;
  justify-content: space-between;
  background: #fff;
  width: 100%;
  
  .logo {
    display: flex;
    height: 60px;
    margin-left: 20px;
  }
  
  .user {
    display: flex;
    align-items: center;
    margin-right: 20px;
    
    .user-info {
      display: flex;
      align-items: center;
      cursor: pointer;
      
      .username {
        margin-left: 8px;
        color: #333;
      }
    }
  }
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.layout-container {
  height: 100vh;
}

.el-aside {
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}

.el-menu-vertical {
  border-right: none;
}

.el-main {
  background-color: #f5f7fa;
  padding: 20px;
}

.el-menu {
    border-right: none; /* 移除默认的右边框 */
  }
  /* 修改选中项的背景颜色和文字颜色 */
  .el-menu .el-menu-item.is-active {
    color: #FA5566 !important;
  }

  /* 修改悬浮时的背景颜色和文字颜色 */
  .el-menu .el-menu-item:hover {
    background-color: #FBEBEB !important;
    color: #606266 !important;
  }
  /* 修改菜单文字大小 */
  .el-menu .el-menu-item span {
    font-size: 16px; /* 根据需要调整字体大小 */
  }
</style>